<template>
  <div class="ques__form">
    <p>新建事故</p>
    <n-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-width="40"
      :show-require-mark="false"
      label-placement="left"
      size="small"
      require-mark-placement="left"
    >
      <template v-for="(item,index) in getFormOptions" :key="index">
        <n-form-item :label="item.label" :path="item.key" v-bind="item?.prop">
          <n-select v-if="item.type === 'select'" v-model:value="form[item.key]" v-bind="item.props" v-on="item.func" />
          <n-input-number v-if="item.type === 'number'" v-model:value="form[item.key]" v-bind="item.props" v-on="item.func" />
          <n-slider v-if="item.type === 'slider'" v-model:value="form[item.key]" v-bind="item.props" v-on="item.func" />
          <n-grid v-if="item.type === 'radio'" x-gap="12" item-responsive :cols="5">
            <n-gi span="4">
              <n-radio-group v-model:value="form[item.key]" :name="item.key" v-on="item.func">
                <n-space>
                  <n-radio v-for="(cItem,cIndex) in item.options" :key="`${item.key}_${cIndex}`" :value="cItem.value"> {{ cItem.label }}</n-radio>
                </n-space>
              </n-radio-group>
            </n-gi>
            <n-gi>
              <n-button color="#c9cdd4" @click="handleRedraw">重绘</n-button>
            </n-gi>
          </n-grid>
        </n-form-item>
      </template>
    </n-form>
    <div class="tabs__button">
      <n-button type="success" @click="handleSave">保存</n-button>
      <n-button text-color="#18a058" @click="handleCancel">取消</n-button>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, toRefs, computed, onMounted, useAttrs } from 'vue'
import { getAirList, getTaskInspectionType } from '@/api/task/index.js'
import { dspServiceList } from '@/api/accident/index.js'
import { getRoadInformation } from '@/api/road/road-manage/index.js'
import { getIdDeptIdRoad } from '@/api/org-manage/depart-manage/index.js'
import { useUserStore } from '@/store/modules/user.js'
export default defineComponent({
  name: 'CreatePanel',
  emits: { close: null },
  setup(props, { emit }) {
    const attrs = useAttrs()
    const formRef = ref()
    const isPolygon = ref(false)
    const airPortList = ref([])
    const questionList = ref([])
    const serviceList = ref([])
    const channelList = ref([])
    const legList = ref([])
    const methodList = ref([
      { label: '点', value: 'Point' },
      { label: '线', value: 'LineString' },
      { label: '面', value: 'Polygon' }
    ])

    const handleChange = (type, e, option) => {
      if (data.backForm[type] !== e) {
        if (type === 'airportId') {
          const { coverage, latitude, longitude, droneId } = option
          data.form.coverage = coverage
          data.form.droneId = droneId
          data.form.latitude = latitude
          data.form.longitude = longitude
        }
        if (type === 'questionId') {
          const { code } = option
          data.form.questionCode = code
        }
        const params = {
          ...data.form,
          key: type,
          operate: null
        }
        isPolygon.value = params.lineType === 'Polygon'
        attrs.onDone(params)
        if (type === 'channelId') {
          fetchLegList(e)
        }
        if (type === 'lineType') {
          data.form.interval = 50
        }
      }
      data.backForm = { ...data.form }
    }

    const data = reactive({
      form: {
        airportId: null,
        lineType: null,
        altitude: 50,
        interval: 50,
        angle: 0,
        questionId: null,
        dspServiceInstId: null,
        channelId: null,
        legId: null
      },
      backForm: {},
      rules: {
        airportId: { required: true, type: 'number', message: '请选择机场', trigger: ['change'] },
        lineType: { required: true, message: '请选择航线绘制方式', trigger: ['change'] },
        questionId: { required: true, message: '请选择事故', trigger: ['change'] },
        dspServiceInstId: { required: true, message: '请选择算法', trigger: ['change'] },
        channelId: { required: true, message: '请选择航道', trigger: ['change'] },
        legId: { required: true, message: '请选择航段', trigger: ['change'] }
      },
      formItem: [
        { type: 'select', key: 'airportId', label: '机场', props: { options: airPortList, labelField: 'name', valueField: 'id', placeholder: '请选机场' }, func: { 'update:value': handleChange.bind(null, 'airportId') }},
        { type: 'radio', key: 'lineType', label: ' ', options: methodList, func: { 'update:value': handleChange.bind(null, 'lineType') }},
        { type: 'number', key: 'altitude', label: '高度', props: { showButton: false }, func: { 'update:value': handleChange.bind(null, 'altitude') }},
        { type: 'slider', key: 'interval', label: '间隔', isShow: isPolygon, props: { max: 300 }, func: { 'update:value': handleChange.bind(null, 'interval') }},
        { type: 'slider', key: 'angle', label: '角度', isShow: isPolygon, props: { max: 360 }, func: { 'update:value': handleChange.bind(null, 'angle') }},
        { type: 'select', key: 'questionId', label: '事故', props: { options: questionList, labelField: 'content', valueField: 'code', placeholder: '请选择事故' }, func: { 'update:value': handleChange.bind(null, 'questionId') }},
        { type: 'select', key: 'dspServiceInstId', label: '算法', props: { options: serviceList, labelField: 'name', valueField: 'dspServiceInstId', placeholder: '请选择算法' }, func: { 'update:value': handleChange.bind(null, 'dspServiceInstId') }},
        { type: 'select', key: 'channelId', label: '航道', props: { options: channelList, labelField: 'name', valueField: 'id', placeholder: '请选择航道' }, func: { 'update:value': handleChange.bind(null, 'channelId') }},
        { type: 'select', key: 'legId', label: '航段', props: { options: legList, labelField: 'legRange', valueField: 'id', placeholder: '请选择航段' }, func: { 'update:value': handleChange.bind(null, 'legId') }}
      ]

    })

    const getFormOptions = computed(() => {
      return data.formItem.filter((item) => {
        const isShow = item.isShow ?? true
        return isShow
      })
    })

    const fetchAirList = async() => {
      const res = await getAirList()
      if (res.code === 0) {
        airPortList.value = res.data.records
        if (res.data.records.length) {
          data.form.airportId = res.data.records[0].id
          handleChange('airportId', data.form.airportId, res.data.records[0])
        }
      } else {
        airPortList.value = []
        data.form.airportId = null
      }
    }

    const fetchTypeList = async() => {
      const res = await getTaskInspectionType()
      if (res.code === 0) {
        questionList.value = res.data
      } else {
        questionList.value = []
      }
    }

    const fetchServiceList = async() => {
      const res = await dspServiceList()
      if (res.code === 0) {
        serviceList.value = res.data
      } else {
        serviceList.value = []
      }
    }

    const fetchChannelList = async() => {
      const res = await getRoadInformation()
      if (res.code === 0) {
        channelList.value = res.data
      } else {
        channelList.value = []
      }
    }

    const fetchLegList = async(channelId) => {
      const userStore = useUserStore()
      const { deptId } = userStore.userInfo
      const res = await getIdDeptIdRoad({ channelId, deptId })
      if (res.code === 0) {
        legList.value = res.data
      } else {
        legList.value = []
      }
    }

    const handleRedraw = () => {
      const params = {
        ...data.form,
        key: 'lineType',
        operate: 'redraw'
      }
      attrs.onDone(params)
    }

    const handleSave = () => {
      formRef.value.validate(async(errors) => {
        if (!errors) {
          const params = {
            ...data.form,
            key: 'lineType',
            operate: 'save'
          }
          attrs.onDone(params)
        } else {
          $message.error('请完善必填信息')
        }
      })
    }

    const handleCancel = () => {
      emit('close')
      attrs.onDone({})
    }

    onMounted(() => {
      fetchAirList()
      fetchTypeList()
      fetchServiceList()
      fetchChannelList()
    })

    return {
      ...toRefs(data),
      formRef,
      isPolygon,
      getFormOptions,
      handleRedraw,
      handleSave,
      handleCancel
    }
  }
})

</script>
<style scoped lang='scss'>
.ques__form{
  padding: 10px;
  color: rgba(255,255,255,1);
  background: rgba(69, 69, 69, 0.5);
  margin-bottom: 15px;
  p{
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
  }
}
::v-deep(.n-form){
  .n-form-item-label,.n-radio__label{
    color: rgba(255,255,255,1);
  }
  .n-input-number{
    width: 100%;
  }
}
::v-deep(.n-grid){
  .n-radio-group{
    line-height: 28px;
  }
}
.tabs__button{
  .n-button+.n-button{
    margin-left:20px;
  }
}
</style>
